package com.learn.mqq.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.learn.mqq.bean.Choice;
import com.learn.mqq.bean.Exam;
import com.learn.mqq.bean.ExamInfo;
import com.learn.mqq.bean.Paper;
import com.learn.mqq.entity.YxExamAnswer;
import com.learn.mqq.entity.YxExamLog;
import com.learn.mqq.entity.YxExamUser;
import com.learn.mqq.entity.YxPaperQuestion;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RocketMQMessageListener(topic = "rocketmq-msg", consumerGroup = "${rocketmq.consumer.group}", messageModel = MessageModel.CLUSTERING)
@Component("consumerService")
public class ConsumerService implements RocketMQListener<String> {

    @Autowired
    private RedisService redisService;

    @Autowired
    private IYxExamUserService iYxExamUserService;

    @Autowired
    private IYxPaperQuestionService iYxPaperQuestionService;

    @Autowired
    private IYxExamAnswerService iYxExamAnswerService;

    @Autowired
    private IYxExamLogService iYxExamLogService;

    @Transactional
    @Override
    public void onMessage(String s) {
        System.out.println("收到消息内容："+s);
        String valueByKey = redisService.getValueByKey(s);
        if (!StrUtil.isEmpty(valueByKey)) {
            ExamInfo examInfo = JSONUtil.toBean(valueByKey, ExamInfo.class);
            Exam exam = examInfo.getExam();
            Paper paper = examInfo.getPaper();
            List<Choice> singleChoice = examInfo.getSingleChoice();
            List<Choice> multipleChoice = examInfo.getMultipleChoice();
            List<Choice> judgeChoice = examInfo.getJudgeChoice();
            List<Choice> mergedList = new ArrayList<>();
            mergedList.addAll(singleChoice);
            mergedList.addAll(multipleChoice);
            mergedList.addAll(judgeChoice);
            String logId = examInfo.getLogId();
            String input = examInfo.getId();
            String[] parts = input.split("-");
            String idCard = parts[1];
            YxExamUser examUser = iYxExamUserService.getOne(new LambdaQueryWrapper<YxExamUser>().eq(YxExamUser::getIdCard, idCard));

            // 获取考试记录
            YxExamLog yxExamLog = iYxExamLogService.getById(logId);
            if (yxExamLog.getStatus() == 1) {
                // 存储答题记录
                for (Choice choice : mergedList) {
                    YxPaperQuestion yxPaperQuestion = iYxPaperQuestionService.getOne(new LambdaQueryWrapper<YxPaperQuestion>().eq(YxPaperQuestion::getId, choice.getId()));
                    YxExamAnswer yxExamAnswer = new YxExamAnswer();
                    yxExamAnswer.setUserId(examUser.getId());
                    yxExamAnswer.setExamLogId(Long.valueOf(logId));
                    yxExamAnswer.setPaperId(paper.getId());
                    yxExamAnswer.setQuestionId(yxPaperQuestion.getId());
                    yxExamAnswer.setAnswer(choice.getUserAnswer());
                    yxExamAnswer.setType(choice.getType());
                    if (areStringsEqual(yxPaperQuestion.getResult(), choice.getUserAnswer())) {
                        yxExamAnswer.setIsRight(1);
                        yxExamAnswer.setScore(getScore(exam, choice.getType()));
                    } else {
                        yxExamAnswer.setIsRight(0);
                        yxExamAnswer.setScore(BigDecimal.valueOf(0));
                    }
                    iYxExamAnswerService.save(yxExamAnswer);
                    System.out.println("答题存储成功："+yxExamAnswer.getId());
                }
                // 存储考试记录
                if (!ObjectUtil.isEmpty(yxExamLog)) {
                    yxExamLog.setScore(iYxExamAnswerService.countScore(examUser.getId(), Long.valueOf(logId)));
                    yxExamLog.setTime(examInfo.getExamTime());
                    yxExamLog.setStatus(2);
                    iYxExamLogService.updateById(yxExamLog);
                    redisService.deleteByKey(s);
                    System.out.println("考试记录存储成功："+yxExamLog.getId());
                } else {
                    System.out.println("error-未查询到考试记录：id="+logId);
                }
            } else {
                System.out.println("error-未查询到考试记录或考试记录已更改：id="+logId);
            }


        }
    }

    public static BigDecimal getScore(Exam exam, Integer type) {
        if (type == 1) {
            return BigDecimal.valueOf(exam.getSingleScore());
        }
        if (type == 3) {
            return BigDecimal.valueOf(exam.getJudgeScore());
        }
        if (type == 2) {
            return BigDecimal.valueOf(exam.getMultipleScore());
        }
        return BigDecimal.valueOf(0);
    }

    public static boolean areStringsEqual(String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();

        Arrays.sort(chars1);
        Arrays.sort(chars2);

        String sortedStr1 = new String(chars1);
        String sortedStr2 = new String(chars2);

        return sortedStr1.equals(sortedStr2);
    }
}
